package com.imy.common.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import butterknife.ButterKnife;

/**
 * Created by 4399-1500 on 2018/2/8.
 */

public abstract class BaseDialog implements LifecycleObserver {
    protected final String TAG = this.getClass().getSimpleName();
    protected Activity mActivity;
    protected AlertDialog mDialog;
    protected LayoutInflater mInflater;

    public BaseDialog(AppCompatActivity activity) {
        this.mActivity = activity;
        this.mInflater = LayoutInflater.from(mActivity);
        mDialog = new AlertDialog.Builder(activity).create();
        if (autoPop()){
            mDialog.show();
        }
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setBackgroundDrawable(activity.getResources().getDrawable(android.R.color.transparent));
        }
        View inflate = mInflater.inflate(getLayoutId(), null);
        mDialog.setContentView(inflate);
        mDialog.setCancelable(true);
        ButterKnife.bind(this, mDialog);
        init(inflate);
        activity.getLifecycle().addObserver(this);
    }

    protected boolean autoPop() {
        return true;
    }

    protected void init(View view) {

    }

    protected abstract int getLayoutId();

    public void dismiss() {
        if (mDialog != null) {
            mDialog.dismiss();
            isShow=false;
        }
    }

    public void show() {
        if (mDialog != null) {
            mDialog.show();
            isShow=true;
        }
    }
    protected boolean isShow =false;
    public AlertDialog getDialog() {
        return mDialog;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        if (isShow){
            dismiss();
        }

    }
}
